package it.blueocean.acanto.platform.dao.impl;

import it.blueocean.acanto.entities.platform.Group;
import it.blueocean.acanto.platform.dao.GroupDao;

import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;

@Named("groupDao")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class GroupDaoImpl implements GroupDao
{
	private final static Logger logger = LoggerFactory.getLogger(GroupDaoImpl.class);

	@PersistenceContext(type = PersistenceContextType.EXTENDED)
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	@Override
	public List<Group> availableGroups(String username)
	{
		return entityManager
				.createQuery("select group from Group group "
				+ "where group.id not in "
				+ "( select group.id from DBUser as user join user.groups as group where user.username = :username )" )
				.setParameter("username", username)
				.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Group> associatedGroups(String username)
	{
		return entityManager
				.createQuery("select group from DBUser as user join user.groups as group where user.username = :username ")
				.setParameter("username", username)
				.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Group> retrieve()
	{
		return entityManager.createQuery("from Group group").getResultList();
	}

	@Override
	public Group retrieve(String groupId)
	{
		return entityManager.find(Group.class, groupId);
	}

	@Override
	public void store(Group group)
	{
		logger.info("Persisting Group [" + group + "]");
		
		entityManager.merge(group);
	}

	@Override
	public void delete(Group group)
	{
		logger.info("Deleting Group [" + group + "]");

		entityManager.remove(group);
	}

}
